//
//  RpayApiManager.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/21.
//  Copyright © 2017年 Charlie. All rights reserved.
//

let kApiParamUserName: String = "userName"

class RpayApiManager: CTAPIBaseManager, CTAPIManager, CTAPIManagerValidator {
    
    override init() {
        super.init()
        validator = self
    }
    
    override func loadData(withParams params: [AnyHashable : Any]?) -> Int {
        var p: [AnyHashable : Any]
        if params != nil {
            p = params!
        } else {
            p = [String: Any]()
        }
        if UserShare.shared.isLogin {
            let user = UserShare.shared.loginUser
            p[kApiParamUserName] = user!.userName
            p["token"] = user!.token
        }
        
        return super.loadData(withParams: p)
    }
    
    // MARK: - API Manager
    /// 服务器地址
    func service() -> CTService! {
        return RPayApiService()
    }
    
    /// 接口
    func methodName() -> String! {
        return ""
    }
    
    /// 请求
    func requestGenerator() -> CTRequestGenerator! {
        return ApiReqGenerator()
    }
    
    /// 请求类型
    func requestType() -> CTAPIManagerRequestType {
        return .post
    }
    
    /// 是否需要缓存
    func shouldCache() -> Bool {
        return false
    }
    
    /// 是否加载本地数据
    func shouldLoadFromNative() -> Bool {
        return false
    }
    
    // MARK: - API Manager Interceptor
    
    override func beforePerformFail(with response: CTURLResponse!) -> Bool {
        let flag = super.beforePerformFail(with: response)
        switch errorType {
        case .noRequest:
            assert(false, "错了！API没有生成Request！")
            break
            
        case .noNetWork:
            self.setValue(ApiLocalStr("无网络"), forKeyPath: "errorMessage")
            break
            
        default:
            break
        }
        return flag
    }
    
    // MARK: - API Manager Validator
    
    func manager(_ manager: CTAPIBaseManager!, isCorrectWithCallBackData data: [AnyHashable : Any]!) -> Bool {
        if data == nil {
            self.setValue(ApiLocalStr("服务器响应异常"), forKeyPath: "errorMessage")
            return false
        }
        
        var flag = false
        
        // 错误码
        let codeStr = data["code"] as? String
        var code: Int = -1
        if codeStr != nil {
            let c = Int(codeStr!)
            if c != nil {
                code = c!
            }
        }
        
        // 错误提示
        let msg = data["msg"] as? String
        if msg != nil {
            self.setValue(ApiLocalStr(msg), forKeyPath: "errorMessage")
        }
        
        let timestamp = data["timestamp"] as? Int64
        if timestamp != nil {
            if let tst = timestamp,
                let nowTimestamp = Int64(NSDate.nowTimestamp)
            {
                InterfaceShare.shared.difftime = tst - nowTimestamp
            }
        }
        
        switch code {
        case 300:
            if msg == nil {
                self.setValue(ApiLocalStr("登录超时"), forKeyPath: "errorMessage")
            }
            DispatchQueue.main.asyncAfter(deadline: .now()+0.6, execute: {
                IFShared().pushLoginVC()
            })
            break
            
        case 400:
            if msg == nil {
                self.setValue(ApiLocalStr("没有权限"), forKeyPath: "errorMessage")
            }
            break
            
        case 500:
            if msg == nil {
                self.setValue(ApiLocalStr("系统内部错误"), forKeyPath: "errorMessage")
            }
            break
        case 600:
            if msg == nil {
                self.setValue(ApiLocalStr("业务错误"), forKeyPath: "errorMessage")
            }
            break
            
        case 202, 201:
            break
            
        default:
            flag = true
            break
        }
        
        return flag
    }
    
    func manager(_ manager: CTAPIBaseManager!, isCorrectWithParamsData data: [AnyHashable : Any]!) -> Bool {
        return true
    }
}
